# app/services/spot_service.py
from typing import List, Optional, Tuple
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from app.models.spot_model import Spot
from app.schemas.spot_schema import SpotCreate, SpotUpdate


class SpotService:
    """景点业务逻辑"""

    # --------------- 基础单条操作 ---------------
    @staticmethod
    def create_spot(db: Session, obj_in: SpotCreate) -> Tuple[int, str, Optional[Spot]]:
        try:
            db_obj = Spot(**obj_in.dict())
            db.add(db_obj)
            db.commit()
            db.refresh(db_obj)
            return 201, "创建成功", db_obj
        except SQLAlchemyError:
            db.rollback()
            return 500, "数据库异常", None
        except Exception:
            db.rollback()
            return 500, "服务器内部错误", None

    @staticmethod
    def get_spot(db: Session, spot_id: int) -> Tuple[int, str, Optional[Spot]]:
        try:
            spot = (
                db.query(Spot)
                .filter(Spot.id == spot_id, Spot.is_deleted == False)
                .first()
            )
            if not spot:
                return 404, "景点不存在", None
            return 200, "查询成功", spot
        except SQLAlchemyError:
            return 500, "数据库异常", None
        except Exception:
            return 500, "服务器内部错误", None

    # --------------- 列表+搜索 ---------------
    @staticmethod
    def list_spots(
        db: Session,
        city: Optional[str] = None,
        keyword: Optional[str] = None,
        skip: int = 0,
        limit: int = 10,
    ) -> Tuple[int, str, List[Spot]]:
        try:
            q = db.query(Spot).filter(Spot.is_deleted == False)
            if city:
                q = q.filter(Spot.city == city)
            if keyword:
                q = q.filter(Spot.name.contains(keyword))
            total = q.count()  # 可扩展返回 total 给分页
            res = q.order_by(Spot.id.desc()).offset(( (skip-1) if (skip - 1) >= 0 else 0) * limit).limit(limit).all()
            return 200, "查询成功", res
        except SQLAlchemyError:
            return 500, "数据库异常", []
        except Exception:
            return 500, "服务器内部错误", []

    # --------------- 更新 ---------------
    @staticmethod
    def update_spot(
        db: Session, spot_id: int, obj_in: SpotUpdate
    ) -> Tuple[int, str, Optional[Spot]]:
        try:
            code, msg, db_obj = SpotService.get_spot(db, spot_id)
            if code != 200:
                return code, msg, None
            for k, v in obj_in.dict(exclude_unset=True).items():
                setattr(db_obj, k, v)
            db.commit()
            db.refresh(db_obj)
            return 200, "更新成功", db_obj
        except SQLAlchemyError:
            db.rollback()
            return 500, "数据库异常", None
        except Exception:
            db.rollback()
            return 500, "服务器内部错误", None

    # --------------- 软删 ---------------
    @staticmethod
    def delete_spot(db: Session, spot_id: int) -> Tuple[int, str]:
        try:
            code, msg, db_obj = SpotService.get_spot(db, spot_id)
            if code != 200:
                return code, msg
            db_obj.is_deleted = True
            db.commit()
            return 200, "删除成功"
        except SQLAlchemyError:
            db.rollback()
            return 500, "数据库异常"
        except Exception:
            db.rollback()
            return 500, "服务器内部错误"